<?php

namespace app\index\business;

use app\index\controller\BaseController;
use app\libs\Functions;
use Curl\Curl;
use think\Config;
use think\Request;

/**
 * 微信
 * Class Industry
 * @package app\index\controller
 */
class Wx extends BaseBusiness
{
    /**
     * 微信授权登录
     */
    public function login(Request $request)
    {

        $code = $request->param('code', '', 'trim');
        if (!$code) {
            return json_encode(['status' => -1, 'msg' => '参数丢失', 'data' => []]);
        }
        $account = db('wx_info')->find();
        /****通过code去获取openid和access_token***/
        // 通过code参数获取Access_Token
        $token = $this->get_access_token($code,$account);
        // 通过code参数获取用户信息
        $info = $this->get_userinfo($token->access_token, $token->openid);
//        $account = db('wx_info')->find();
//        $info=$this->get_userinfo(trim($account['access_token']),'ol4m81dqlTNF7sVgjtCP8VLcE1Rw');
//        dd($info);
        // $info即为已经获得的用户的信息，数据格式为对象形式。如获取用户的openid,获取方式为$info->openid
        $user=db('user')->where(['status'=>1,'openid'=>$info->openid])->find();
        if (empty($user['user_no'])){
            db('user')->insert(['openid'=>$info['openid'],'nickname'=>$info['nickname'],'avatar'=>$info['headimgurl'],'sex'=>$info['sex']]);
            return json_encode(['status' => -1, 'msg' => '这是一个新用户', 'data' => ['open_id' => $info->openid]]);
        }
        $token=$this->getBusiness('user')->userAfterLogin($user);
        $token['phone']=$user['phone'];
        return json_encode(['status' => 1, 'msg' => 'Suceess', 'data' =>$token]);
    }


    /***获取7200秒的access_token**/
    public function get_access_token()
    {
        $wx=db('wx_info')->find();
        if ($wx['expire_time']>time()){
            return $wx['access_token'];
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        $params=[
            'grant_type'=>'client_credential',
            'secret'=>trim($wx['sercet']),
            'appid'=>trim($wx['appid']),
        ];
        $res=httpRequest($url,'GET',$params);
        $exp=bcadd(time(),7200,0);
        db('wx_info')->where('id',$wx['id'])->update(['expire_time'=>$exp,'access_token'=>$res['access_token']]);
        return $res['access_token'];
    }

    /**
     * 根据access_token以及oppenid获取用户信息
     */
    public function get_userinfo($access_token,$oppenid)
    {
        $url='https://api.weixin.qq.com/cgi-bin/user/info';
        $data=[
            'access_token'=>$access_token,
            'openid'=>$oppenid,
            'lang'=>'zh_CN'
        ];

        $res = httpRequest($url,'GET',$data);
        return $res;
    }
}